package org.xmx0632.flywayside;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import org.xmx0632.flywayside.constant.Constant;

import java.io.File;
import java.io.FileFilter;

/**
 * @author xmx0632
 * 
 *         TODO 根据sql模版和配置项信息，生成sql脚本小工具
 *         <p>
 * 
 *         <pre>
 * ALTER table $$$ add COLUMN DESC varchar(10) not null;
 * 下标起始值，下标结束值，前缀，是否需要填充N位空值（1-> 001,2-> 002）
 *
 *
 *
 * ALTER table ${tableName0} add COLUMN DESC varchar(10) not null;
 * ALTER table ${tableName1} add COLUMN DESC varchar(10) not null;
 * ALTER table ${tableName2} add COLUMN DESC varchar(10) not null;
 * ALTER table ${tableName3} add COLUMN DESC varchar(10) not null;
 *
 *         </pre>
 */

@Mojo(name = "generatesql")
public class FlywaySideGenerateSqlScriptMojo extends AbstractMojo {

	@Parameter(defaultValue = "###")
	private String templatePlaceHolder;

	@Parameter(defaultValue = "${tableName")
	private String templateTablePrefix;

	@Parameter(defaultValue = "}")
	private String templateTableSuffix;

	@Parameter(defaultValue = "1")
	private Integer templateStartIndex;

	@Parameter(defaultValue = "1")
	private Integer templateEndIndex;

	/**
	 * 1:不填充；>1：用0填充左边空位
	 */
	@Parameter(defaultValue = "1")
	private Integer templatePaddingNumber;

	@Parameter(defaultValue = "target/sql")
	private File templateOutputDirectory;

	@Parameter(defaultValue = "src/main/resources/sql/template")
	private File templateSqlDirectory;

	@Override
	public void execute() throws MojoExecutionException {
		getLog().info("\n\nusage:\n" + Constant.SPLITTER);
		printUsage();

		getLog().debug("templatePlaceHolder:" + templatePlaceHolder);
		getLog().debug("templateTablePrefix:" + templateTablePrefix);
		getLog().debug("templateTableSuffix:" + templateTableSuffix);
		getLog().debug("templatePaddingNumber:" + templatePaddingNumber);
		getLog().debug("templateOutputDirectory:" + templateOutputDirectory.getAbsolutePath());
		getLog().debug("templateSqlDirectory:" + templateSqlDirectory.getAbsolutePath());

		try {
			File[] templateFiles = templateSqlDirectory.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.isFile() && pathname.getName().endsWith(".sql");
				}
			});

			if (templateFiles == null) {
				getLog().error("no template file found in " + templateSqlDirectory.getAbsolutePath());
				return;
			}
			getLog().info(templateFiles.length + " templateFiles found");

			for (int i = 0; i < templateFiles.length; i++) {
				File templateFile = templateFiles[i];
				String content = FileUtils.fileRead(templateFile, "utf-8");
				getLog().info(templateFile.getName() + " content:\n" + content);

				StringBuilder allTargetSql = new StringBuilder(256);
				for (int j = templateStartIndex; j <= templateEndIndex; j++) {

					String format = "%0" + templatePaddingNumber + "d";
					String index = String.format(format, j);
					String templateReplaceString = templateTablePrefix + index + templateTableSuffix;

					String targetSql = StringUtils.replace(content, templatePlaceHolder, templateReplaceString);
					allTargetSql.append(targetSql);
					allTargetSql.append("\n");
				}

				getLog().info(templateFile.getName() + " generated in " + templateOutputDirectory + ".");
				getLog().debug(templateFile.getName() + " target sql:\n" + allTargetSql);

				if (!templateOutputDirectory.exists()) {
					templateOutputDirectory.mkdirs();
				}
				File targetFile = new File(templateOutputDirectory, templateFile.getName());
				getLog().debug("targetFile:" + targetFile);

				FileUtils.fileWrite(targetFile.getAbsolutePath(), "utf-8", allTargetSql.toString());
			}

		} catch (Exception e) {
			getLog().error(e.getMessage(), e);
		}
	}

	public void printUsage() {
		String usage = "生成sql模版脚本:\n\n";
		getLog().info(usage);
	}

}
